const app = getApp(),
  {
    validate
  } = require("../../../../utils/validate");

const stateOptions = [{
    value: 1,
    name: "正常"
  },
  {
    value: 2,
    name: "注销"
  },
]

Page({

  /**
   * 页面的初始数据
   */
  data: {
    areaInfo_name: [],
    area_id_Info: [],
    franchisees: [],
    type: "",
    selected: [],
    authIndex: "",
    data: "",
    authPicker: [{
      value: 0,
      name: "普通"
    }, {
      value: 1,
      name: "高级"
    }],
    stateOptions,
    stateIndex: ''
  },

  onReady: function () {
    this.cascade = this.selectComponent("#cascade")
  },

  showCascade() {
    this.cascade.selection(this.data.area_id_Info);
  },

  cascadeComplete(e) {
    const detail = e.detail;
    this.setData({
      areaInfo_name: detail.names,
      area_id_Info: detail.ids
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let {
      type,
      id = ""
    } = options;
    this.id = id;
    if (type == 1 || type == 2) {
      this.getFranchiseeList(type);
    } else {
      if (this.id) {
        this.getEngineerInfo();
      }
    }
    this.setData({
      type,
      pageType: id ? 2 : 1
    })
    wx.setNavigationBarTitle({
      title: this.data.pageType == 1 ? '添加维修员' : '编辑维修员',
    })
  },


  getEngineerInfo() {
    app.ajax({
      url: "Partner/EquipmentManagement/detail",
      data: {
        id: this.id
      },
      success: res => {
        if (res.data.code == 1000) {
          const data = res.data.data;
          const type = this.data.type;
          if (type == 1 || type == 2) {
            if (data.franchiser.length > 0) {
              const france = [],
                selected = [];
              data.franchiser.forEach(i => france.push(i.id));
              const franchisees = this.data.franchisees;
              franchisees.forEach((item, index) => {
                if (france.includes(item.id)) {
                  franchisees[index].checked = true;
                  selected.push(item);
                }
              })
              franchisees.sort((a, b) => {
                return Boolean(b.checked) - Boolean(a.checked)
              });
              this.setData({
                franchisees,
                selected
              })
            }
          }
          let stateIndex = this.data.stateOptions.findIndex(current => current.value == data.state)
          let authIndex = this.data.authPicker.findIndex(i => i.value == data.is_auth)
          this.setData({
            data,
            area_id_Info: [data.province_code, data.city_code, data.area_code],
            areaInfo_name: [data.province, data.city, data.area],
            authIndex,
            stateIndex
          })
        } else {
          app.showToast(res.data.message)
        }
      },
      error: e => {
        app.showToast("网络错误!请稍后再试~~~");
      }
    })
  },

  //获取合伙人下面的加盟商
  getFranchiseeList(type) {
    app.ajax({
      url: 'Partner/EquipmentManagement/all_franchiser',
      data: {
        type
      },
      success: res => {
        if (res.data.code == 1000) {
          this.setData({
            franchisees: res.data.data
          })
          if (this.id != "") {
            this.getEngineerInfo();
          }
        } else {
          app.showToast(res.data.mesage)
        }
        console.log(res)
      },
      error: err => {
        app.showToast("网络错误!请稍后再试~~~");
      }
    })
  },

  //选择地址
  addressChange(e) {
    this.setData({
      areaInfo_name: e.detail.address.areaInfo_name,
      area_id_Info: e.detail.address.area_id_Info,
    });
  },


  //选择
  bindPickerChange(e) {
    const name = e.currentTarget.dataset.name;
    this.setData({
      [name]: e.detail.value
    })
  },




  //显示POP
  showPop() {
    this.setData({
      popupShow: true
    })
  },


  //隐藏POP
  hidePopup() {
    this.setData({
      popupShow: false
    })
  },

  //POP确定
  submitCheck() {
    const list = this.data.franchisees;
    const result = list.filter(item => {
      return !!item.checked;
    })
    this.setData({
      selected: result,
      popupShow: false
    })
  },



  //点击徽章
  chooseItem(e) {
    const {
      index
    } = e.currentTarget.dataset;
    let franchisees = this.data.franchisees;
    franchisees[index].checked = !franchisees[index].checked;
    this.setData({
      franchisees
    })
  },


  searchInputConfrim(e) {

  },

  //全选操作
  checkedAll() {
    this.baseCheck();
  },
  //置空=全不选操作
  restCheck() {
    this.baseCheck(-1);
  },

  //反选操作
  reverseCheck() {
    this.baseCheck(0);
  },


  baseCheck(type = 1) {
    const search = this.data.search;
    let list = this.data.franchisees;
    if (search !== "") {
      list.map((item, index) => {
        if (!item.hidden) {
          if (type == 1) {
            return item.checked = true;
          } else if (type == -1) {
            return item.checked = false;
          } else if (type == 0) {
            return item.checked = !item.checked
          }
        }

      })
    } else {
      list.map((item, index) => {
        if (type == 1) {
          return item.checked = true;
        } else if (type == -1) {
          return item.checked = false;
        } else if (type == 0) {
          return item.checked = !item.checked
        }
      })
    }
    this.setData({
      franchisees: list
    })
  },





  //园区搜索
  searchInput(e) {
    console.log(e.detail.value);
    const name = e.detail.value.trim();
    const list = this.data.franchisees;
    if (name === "") { //清空搜索内容会map所有内容显示，然后将勾选的排序到最上面
      list.map((item, index) => {
        return item.hidden = false;
      })
      list.sort((a, b) => {
        return Boolean(b.checked) - Boolean(a.checked);
      })
    } else {
      list.forEach((item, index) => {
        let conditionName = !item.account_name.includes(name);
        if (conditionName) {
          list[index].hidden = true;
        }
      })
    }
    this.setData({
      search: name,
      franchisees: list
    })
  },


  formSubmit(e) {
    const form = e.detail.value;
    console.log(form);
    if (validate._isNullOrEmpty(form.name)) {
      app.showToast("请填写姓名");
      return;
    }
    if (validate._isNullOrEmpty(form.account)) {
      app.showToast("请填写账号");
      return;
    }
    if (this.id == "") {
      if (validate._isNullOrEmpty(form.password)) {
        app.showToast("请填写密码");
        return;
      }
    }
    if (validate._isNullOrEmpty(form.phone)) {
      app.showToast("请填写电话");
      return;
    }

    if (!validate._isMobile(form.phone)) {
      app.showToast("电话号码格式错误");
      return;
    }
    // if (validate._isNullOrEmpty(form.idcard)) {
    //   app.showToast("请填写身份证号码");
    //   return;
    // }
    // if (!validate._isIdCard(form.idcard)) {
    //   app.showToast("身份证号码格式错误");
    //   return;
    // }
    if (this.data.area_id_Info.length == 0) {
      app.showToast("请选择地址");
      return;
    }
    if (validate._isNullOrEmpty(form.address)) {
      app.showToast("请填写详细地址");
      return;
    }
    if (this.data.authIndex === '') {
      app.showToast("请选择权限");
      return;
    }
    if (this.data.pageType == 2 && this.data.stateIndex === "") {
      app.showToast("请选择状态");
      return;
    }
    const type = this.data.type;
    if (type == 1 || type == 2) {
      const selected = this.data.selected;
      if (selected.length == 0) {
        app.showToast("请选择加盟");
        return;
      }
      let franchiser = [];
      selected.forEach(i => franchiser.push(Number.parseInt(i.id)));
      form.franchiser = franchiser;
    }
    form.type = this.data.type;
    let [province, city, area] = this.data.areaInfo_name
    let [province_code, city_code, area_code] = this.data.area_id_Info;
    Object.assign(form, {
      province,
      city,
      area
    }, {
      province_code,
      city_code,
      area_code
    });
    let url = "Partner/EquipmentManagement/add";
    if (this.id != "") {
      if (form.password == "") {
        delete form.password;
      }
      form.state = this.data.stateOptions[this.data.stateIndex].value;
      form.is_auth = this.data.authPicker[this.data.authIndex].value;
      form.id = this.id;
      url = "Partner/EquipmentManagement/edit";
    }
    wx.showLoading({
      mask: true
    })
    app.ajax({
      url,
      data: form,
      success: res => {
        wx.hideLoading();
        if (res.data.code == 1000) {
          app.showToast(res.data.message, "success");
          let pages = getCurrentPages();
          let targetPage = pages[pages.length - 2];
          targetPage.page = 1;
          targetPage.setData({
            list: []
          })
          targetPage.getEngineeringList();
          // targetPage.onLoad(targetPage.options)
          setTimeout(() => {
            wx.navigateBack();
          }, 2000)
        } else {
          app.showToast(res.data.message);
        }
      },
      error: e => {
        wx.hideLoading();
        app.showToast("网络错误!请稍后再试~~~")
      }
    })

  },
})